package com.pwc.conversionTool.controller;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobKey;
import com.pwc.GAE.blobstore.BlobstoreManager;
import com.pwc.conversionTool.biz.DataAdaptorBiz;
import com.pwc.conversionTool.entity.CsvDataType;
import com.pwc.conversionTool.entity.DataTemplate;
import com.pwc.conversionTool.entity.ExcelDataType;
import com.pwc.conversionTool.entity.Formula;

import static com.pwc.GAE.blobstore.BlobstoreUtil.*;
import static com.pwc.conversionTool.controller.sessionPersistence.AccountSessionPersistence.*;

@Controller
public class DataAdaptorController {

	private static final Logger logger = LoggerFactory.getLogger(DataAdaptorController.class);

	@Autowired
	public ServletContext context;

	private DataAdaptorBiz biz = new DataAdaptorBiz();

	private BlobstoreManager manager;

	@RequestMapping(value = "/dataAdaptor/setup", method = RequestMethod.GET)
	public String dataAdaptor(Locale locale, Model model, HttpSession session) {
		if (!isLogin(session)) {
			return "account/login";
		}

		return "dataAdaptor/setup";
	}

	@RequestMapping(value = "/dataAdaptor/csvType", method = RequestMethod.GET)
	public String csvType(Locale locale, Model model, HttpSession session) {
		if (!isLogin(session)) {
			return "account/login";
		}
		
		model.addAttribute("updateURL", createUploadUrl("/dataAdaptor/csvTypeUpload"));
		model.addAttribute("isEdit", true);
		model.addAttribute("dataAdaptorId", 0);
		
		return "dataAdaptor/csvType";
	}
	
	
	@RequestMapping(value = "/dataAdaptor/excelType", method = RequestMethod.POST)
	public String excelType( Long dataAdaptorId,boolean isEdit,Locale locale, Model model, HttpSession session) {
		if (!isLogin(session)) {
			return "account/login";
		}
		
		DataTemplate dataTemplate= biz.getDataAdaptorById(dataAdaptorId);
		ExcelDataType excelDataType=biz.getExcelDataType(dataTemplate);
		model.addAttribute("updateURL", createUploadUrl("/dataAdaptor/excelTypeUpload"));
		model.addAttribute("isEdit", isEdit);
		model.addAttribute("dataAdaptor", dataTemplate);
		model.addAttribute("excelDataType", excelDataType);	
		return "dataAdaptor/excelType";
	}
	
	
	
	
	@RequestMapping(value = "/dataAdaptor/csvType", method = RequestMethod.POST)
	public String csvTypePost( Long dataAdaptorId,boolean isEdit,Locale locale, Model model, HttpSession session) {
		if (!isLogin(session)) {
			return "account/login";
		}
		
		try {
			DataTemplate dataTemplate= biz.getDataAdaptorById(dataAdaptorId);	
			CsvDataType csvDataType=biz.getCsvDataTypeByDataTemplate(dataTemplate);
			model.addAttribute("csvDataType", csvDataType);		
			model.addAttribute("updateURL", createUploadUrl("/dataAdaptor/csvTypeUpload"));
			model.addAttribute("isEdit", isEdit);
			model.addAttribute("dataAdaptor", dataTemplate);
			
			
			if(csvDataType!=null&&csvDataType.getColumnSepatator()!=null&&csvDataType.getLineSeparator()!=null)
			{
				model.addAttribute("isDefault", false);
			}else{
				model.addAttribute("isDefault", true);	
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage());
			logger.error(Arrays.toString(e.getStackTrace()));
		}
		
		
		return "dataAdaptor/csvType";
	}
	
	

	@RequestMapping(value = "/dataAdaptor/xmlType", method = RequestMethod.GET)
	public String xmlType(Locale locale, Model model, HttpSession session) {
		if (!isLogin(session)) {
			return "account/login";
		}

		return "dataAdaptor/xmlType";
	}

	@RequestMapping(value = "/dataAdaptor/dataBaseType", method = RequestMethod.GET)
	public String dataBaseType(Locale locale, Model model, HttpSession session) {
		if (!isLogin(session)) {
			return "account/login";
		}

		return "dataAdaptor/dataBaseType";
	}

	/**
	 * 
	 * @param fileName
	 * @param file
	 * @param locale
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dataAdaptor/csvTypeUpload", method = RequestMethod.POST)
	public String uploadProcess(@RequestParam("lineSeparator") String lineSeparator,
			@RequestParam("columnSepatator") String columnSepatator, 
			@RequestParam("adaptorName") String adaptorName,
			@RequestParam("description") String description,
			@RequestParam("id") Long id,
			HttpServletRequest req, Locale locale, Model model, HttpSession session) {
		String message = "";
		DataTemplate dataAdaptor=null;
		try {
			manager = new BlobstoreManager(req);
			BlobInfo info = manager.getSingleBlobInfo("file");

			if (info.getSize() > 0) {
				InputStream in =  getBlobstoreInputStream(manager.getSingleBlobKey("file")) ;
				CsvDataType csvDataType = biz.saveCsvType(lineSeparator, columnSepatator, in,id, adaptorName,description);		
				deleteBlob(info.getBlobKey());
				dataAdaptor=biz.getDataAdaptorById(id);
				message = "upload success!";
				model.addAttribute("msg", message);				
				model.addAttribute("updateURL", createUploadUrl("/dataAdaptor/csvTypeUpload"));
				model.addAttribute("csvDataType", csvDataType);	

			} else {
				message = " failed to upload , because the file was empty.";
			}

		} catch (Exception e) {
			
			logger.error(e.getMessage());
			System.out.println("Error Msg:" + e.getMessage());
			logger.error(Arrays.toString(e.getStackTrace()));
		}
		
		model.addAttribute("msg", message);
		//send back the url
		model.addAttribute("updateURL", createUploadUrl("/dataAdaptor/csvTypeUpload"));
		model.addAttribute("isEdit", false);
		model.addAttribute("dataAdaptor", dataAdaptor);	
		model.addAttribute("isDefault",(lineSeparator.isEmpty()&&columnSepatator.isEmpty()));
		return "dataAdaptor/csvType";
	}

	@RequestMapping(value = "/dataAdaptor/dataAdaptorManager", method = RequestMethod.GET)
	public String dataAdaptorManager(Locale locale, Model model, HttpSession session) {
		if (!isLogin(session)) {
			return "account/login";
		}

		return "dataAdaptor/dataAdaptorManager";
	}

	
	
	/**
	 * 
	 * @param fileName
	 * @param file
	 * @param locale
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dataAdaptor/excelTypeUpload", method = RequestMethod.POST)
	public String excelTypeUpload(
			@RequestParam("sheetName") String sheetName,
			@RequestParam("adaptorName") String adaptorName,
			@RequestParam("description") String description,
			@RequestParam("id") Long id,
			HttpServletRequest req, Locale locale, Model model, HttpSession session) {
		String message = "";
		DataTemplate dataAdaptor=null;
		
		ExcelDataType excelDataType=null;
		try {
			dataAdaptor=biz.getDataAdaptorById(id);
			manager = new BlobstoreManager(req);
			BlobInfo info = manager.getSingleBlobInfo("file");
			String fileName = info.getFilename();

			if (info.getSize() > 0) {
				InputStream in =  getBlobstoreInputStream(manager.getSingleBlobKey("file")) ;
				excelDataType = biz.saveExcelType(fileName, sheetName, in,id, adaptorName,description);		
				deleteBlob(info.getBlobKey());
				
				message = "upload success!";
				model.addAttribute("msg", message);				
				//model.addAttribute("updateURL", createUploadUrl("/dataAdaptor/excelTypeUpload"));
				model.addAttribute("excelDataType", excelDataType);	
				model.addAttribute("isEdit", false);
			} else {
				message = " failed to upload , because the file was empty.";
			}

		} catch (Exception e) {
			
			logger.error(e.getMessage());
			message = " failed to upload , because the sheetname was empty. Please refresh and try again";
			logger.error(Arrays.toString(e.getStackTrace()));
			model.addAttribute("isEdit", true);
			model.addAttribute("dataAdaptor", dataAdaptor);
			model.addAttribute("excelDataType", excelDataType);	
		}
		
		model.addAttribute("msg", message);
		//send back the url
		model.addAttribute("updateURL", createUploadUrl("/dataAdaptor/excelTypeUpload"));	
		model.addAttribute("dataAdaptor", dataAdaptor);	
		return "dataAdaptor/excelType";
	}
	
	
	
	@RequestMapping(value = "/dataAdaptor/filter", method = RequestMethod.GET)
	public String filter(Long dataTemplateId,  Locale locale, Model model, HttpSession session) {
		if (!isLogin(session)) {
			return "account/login";
		}
		
		DataTemplate dataTemplate=biz.getDataAdaptorById(dataTemplateId);
		
		
		
		model.addAttribute("dataTemplate", dataTemplate);
		
		

		return "dataAdaptor/filter";
	}
	
	
	
	
	@RequestMapping(value = "/dataAdaptor/formula", method = RequestMethod.GET)
	public String formula(Long dataTemplateId, Locale locale, Model model, HttpSession session) {
		if (!isLogin(session)) {
			return "account/login";
		}
		
		DataTemplate dataTemplate=biz.getDataAdaptorById(dataTemplateId);
		
		model.addAttribute("dataTemplate", dataTemplate);
		

		return "dataAdaptor/formula";
	}
	
	
	
	
}
